package com.xpq.petserver.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xpq.petserver.exception.AppException;
import com.xpq.petserver.exception.AppExceptionCodeMsg;
import com.xpq.petserver.util.JwtUtil;
import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 设置jwt拦截器验证用户身份
 */
public class JwtInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
        String token = request.getHeader("token");
        if(token == null || "".equals(token)) {
            // 未登录
            throw new AppException(AppExceptionCodeMsg.NOT_LOGIN);
        }
        try{
            // 验证成功
            JwtUtil.verify(token);
            return true;
        }catch (ExpiredJwtException e) {
            // 登录过期
            throw new AppException(AppExceptionCodeMsg.LOGIN_EXPIRATION);
        }catch (Exception e) {
            // 身份验证失败
            throw new AppException(AppExceptionCodeMsg.AUTHENTICATION_FAILURE);
        }
    }
}
